<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SessionsController extends Controller
{
    public function __construct() {
        $this->middleware('guest')->only('create');
        $this->middleware('throttle:10,10')->only('store');
    }

    //登录页
    public function create(){
        return view('sessions.create');
    }
    public function store(Request $request){
        $credentials = $this->validate($request,[
            'email' => ['required','email','max:255'],
            'password'=>['required']
        ]);
        if(Auth::attempt($credentials,$request->has('remember'))){
            if(Auth::user()->activated){
                session()->flash('success','您好，欢迎回来');
                $fallback = route('users.show',Auth::user());
                return redirect()->intended($fallback);
            }else{
                Auth::logout();
                session()->flash('warning','你的账号还未激活，请先前往邮箱激活账号');
            }

        }else{
            session()->flash('danger','账号或密码不匹配');
            return redirect()->back()->withInput();
        }
    }
    public function destroy(){
        Auth::logout();
        session()->flash('success','退出成功');
        return redirect()->route('login');
    }
}
